

import React, { useCallback, useEffect, useState } from 'react'
import { useSelector } from 'react-redux';

import { Input, Space, List, Divider  } from 'antd';
import InfiniteScroll from 'react-infinite-scroll-component';
import { AudioOutlined } from '@ant-design/icons';
import "./LiveRoomChat.scss"


const { Search } = Input;


export default function LiveRoomChat(props) {

  const dispatcher = props.dispatcher;
  const roomInfo = props.state.roomInfo;
  const msgs = props.state.msgs;
  const [ws,setWs] = useState({});
  const user = useSelector(state=>state.user);

  useEffect(()=>{
    if(!roomInfo.wsAddr)return ;
    dispatcher({
      type: "clearMsgs"
    });
    let ws;
    const f =  async() => {
        ws = new WebSocket(`${roomInfo.wsAddr}/${user.userId}/${user.name}`);
        setWs(ws);
        ws.onopen = () => {
            console.log("成功接入聊天室");
        }
        ws.onmessage = (e) => {
            if(e.data.match("viewers#")){
                dispatcher({
                  type: "changeViewers",
                  viewers: parseInt(e.data.slice(8))
                })
                return ;
            }
            dispatcher({
              type: "addMsg",
              msg: e.data
            })
        }
        ws.onclose = () => {
            console.log("连接关闭");
        }
    };
    f();
    return () => {
        ws.close();
    }
  },[roomInfo]);
  const sendMsg = useCallback((value)=>{
    if(!value)return ;
    ws.send(value);
  });

  return (
    <div className='LiveRoomChat-container'>
      <div id='scrollableDiv'>
        <InfiniteScroll
          dataLength={msgs.length}
          endMessage={<Divider plain>It is all, nothing more 🤐</Divider>}
          scrollableTarget="scrollableDiv"
        >
          <List
            itemLayout="horizontal"
            dataSource={msgs}
            renderItem={item => (
              <List.Item>
                <List.Item.Meta
                  description={item}
                />
              </List.Item>
            )}
          />
        </InfiniteScroll>
      </div>

      <Search
        placeholder="请输入内容"
        allowClear
        enterButton="发送"
        size="middle"
        onSearch={sendMsg}
      />
    </div>
  )
}
